module ActiveRecord
  module UserMonitor
    def self.included(base)
      base.class_eval do
        alias_method_chain :create, :user
        alias_method_chain :update, :user
        
        def current_profile_id
          Thread.current[:profile_id]
        end

        def current_client_id
          Thread.current[:client_id]
        end
      end
    end

    def create_with_user
      profile_id = current_profile_id || Profile::SYSTEM
      self[:created_by] = profile_id if self.respond_to?(:created_by) 
      self[:updated_by] = profile_id if self.respond_to?(:updated_by) 
			self[:client_id]  = current_client_id if self.respond_to?(:client_id) && self[:client_id].nil?
      create_without_user
    end
                  
    def update_with_user
      profile_id = current_profile_id || Profile::SYSTEM
      self[:updated_by] = profile_id if self.respond_to?(:updated_by)
      update_without_user
    end
  end
end

ActiveRecord::Base.send :include, ActiveRecord::UserMonitor
